from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
from data.api.env import MAIL_ENV


def send_email(host, port, sender, code, receivers, subject, content, attachment_path):
# 创建邮件
    mail = MIMEMultipart()
    mail['From'] = sender
    mail['To'] = ', '.join(receivers) # 这只是为了显示，实际发送时不需要
    mail['Subject'] = subject
# 添加附件
    with open(attachment_path, 'r', encoding='utf-8') as file:
        report = file.read()
    attachment = MIMEText(report, 'html', 'utf-8') # 如果附件是 HTML，则使用 'html'
    attachment['Content-Disposition'] = f'attachment; filename="{attachment_path.split("/")[-1]}"'
    mail.attach(attachment)
     # 添加正文
    body = MIMEText(content, "html", "utf-8")
    mail.attach(body)
 # 发送邮件
    try:
        smtp = smtplib.SMTP_SSL(host, port) # 使用 SMTP_SSL 类进行 SSL 连接
        smtp.login(sender, code)
        smtp.sendmail(sender, receivers, mail.as_string())
        smtp.quit() # 使用 quit() 而不是 close()，但 close() 通常也可以
        print("邮件发送完毕")
    except Exception as e:
        print(f"邮件发送失败: {e}")

if __name__ == "__main__":
    # 邮箱设置
    host = 'MAIL_ENV["邮件服务商主机"]'
    port = MAIL_ENV["邮件服务商端口号"] # 使用 SSL 连接
    sender = 'MAIL_ENV["1656582652@qq.com"]'
    code = 'MAIL_ENV["ermffbwqyuuadejd"]' # 确保这是正确的授权码
    receivers = [MAIL_ENV["1309257219@qq.com"]] # 直接使用列表
     # 邮件内容
    subject = MAIL_ENV["测试报告"]
    content = MAIL_ENV[""" 
    <p>Dear 经理:</p > 
    <br> 
    <p>自动化测试报告第一期已经完成，请查收</p ><br> 
    <p>此致</p > 
    <p>敬礼</p > 
    <p>张三</p > 
    """]
    attachment_path = MAIL_ENV['maile_tools.py']
 # 发送邮件
    send_email(host, port, sender, code, receivers, subject, content, attachment_path)
